import { login, getUserInfo } from '@/api/sys'
import { setItem, getItem, removeAllItem } from '@/utils/storage'
import { setTokenTime } from '@/utils/auth'
import { TOKEN } from '@/constant'
import router, { removeRouter } from '@/router'
import md5 from 'md5'
export default {
  namespaced: true,
  state: () => ({
    token: getItem(TOKEN) || '',
    userInfo: {}
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      setItem(TOKEN, token)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    handleLogin(ctx, userInfo) {
      const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        login({
          username,
          password: md5(password)
        })
          .then((resp) => {
            ctx.commit('setToken', resp.token)
            // 保存token获取的时间戳
            setTokenTime()
            router.push('/')
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    async getUserProfile(ctx) {
      const resp = await getUserInfo()
      ctx.commit('setUserInfo', resp)
      return resp
    },
    /**
     * 退出登录
     */
    loginOut(ctx) {
      removeRouter()
      ctx.commit('setToken', '')
      ctx.commit('setUserInfo', {})
      removeAllItem()
      // todo 退出登录操作
      router.push('/login')
    }
  }
}
